import { NextRequest } from 'next/server';
import { sqliteDb } from '@/lib/sqlite-database';

export async function POST(request: NextRequest) {
  try {
    await sqliteDb.ensureInitialized();

    // 创建参数表
    await sqliteDb.run(`
      CREATE TABLE IF NOT EXISTS parameters (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        device_id TEXT NOT NULL,
        table_type TEXT NOT NULL,
        sequence INTEGER,
        parameter_name TEXT,
        example_description TEXT,
        data_type TEXT,
        measurement_class TEXT,
        measurement_unit TEXT,
        data_source TEXT,
        parameter_value TEXT,
        validation_status TEXT DEFAULT 'pending',
        validation_message TEXT,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
      )
    `);

    // 创建设备表
    await sqliteDb.run(`
      CREATE TABLE IF NOT EXISTS devices (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        device_id TEXT UNIQUE NOT NULL,
        name TEXT NOT NULL,
        specialty TEXT NOT NULL,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
      )
    `);

    // 创建计量单位表
    await sqliteDb.run(`
      CREATE TABLE IF NOT EXISTS measurement_units (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        unit_class TEXT NOT NULL,
        unit_name TEXT NOT NULL,
        unit_symbol TEXT,
        description TEXT,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
      )
    `);

    return new Response(JSON.stringify({ success: true }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' },
    });
  } catch (error) {
    console.error('Error rebuilding schema:', error);
    return new Response(JSON.stringify({ 
        success: false, 
      error: '重建数据库模式失败：' + (error instanceof Error ? error.message : String(error))
    }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' },
    });
  }
} 